<template>
  <el-drawer
    v-model="dialogVisible"
    title="添加房租位置"
    direction="rtl"
    size="50%"
  >
    <div class="bind-content">
      <div class="group-info">
        <h3>分组信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="组别名称">{{ groupInfo.groupName }}</el-descriptions-item>
          <el-descriptions-item label="用途">{{ groupInfo.usage }}</el-descriptions-item>
          <el-descriptions-item label="计费单价">{{ groupInfo.billingMethod }}</el-descriptions-item>
          <el-descriptions-item label="比例">{{ groupInfo.proportion }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="rent-selection" style="margin-top: 20px;">
        <h3>选择房租位置</h3>
        <div style="margin-bottom: 16px;">
          <el-input 
            v-model="searchText" 
            placeholder="搜索房租名称"
            style="width: 300px; margin-right: 16px;"
            clearable
          />
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button type="success" @click="handleOpenLocationManage" style="margin-left: 8px;">
            <el-icon><Plus /></el-icon>
            新增地点位置
          </el-button>
          <el-button type="primary" @click="addNewRentRow" style="margin-left: 8px;">
            <el-icon><Plus /></el-icon>
            添加房租
          </el-button>
        </div>

        <el-table
          ref="rentTableRef"
          :data="filteredRents"
          @selection-change="handleSelectionChange"
          height="400"
          border
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="房租名称" prop="rentName" width="150">
            <template #default="{ row }">
              <el-input v-model="row.rentName" placeholder="请输入房租名称" />
            </template>
          </el-table-column>
          <el-table-column label="面积(㎡)" prop="area" width="120">
            <template #default="{ row }">
              <el-input v-model="row.area" placeholder="请输入面积" type="number" />
            </template>
          </el-table-column>
          <el-table-column label="位置" prop="location" min-width="200">
            <template #default="{ row, $index }">
              <el-select 
                v-model="row.location" 
                placeholder="请选择房租位置"
                clearable
                filterable
                @change="handleLocationChange(row, $index)"
              >
                <el-option
                  v-for="location in availableLocations"
                  :key="location.id"
                  :label="location.fullPath"
                  :value="location.fullPath"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="status" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === '可用' ? 'success' : 'warning'">
                {{ row.status }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>

        <div style="margin-top: 16px;">
          <el-text type="info">
            已选择 {{ selectedRents.length }} 个房租
          </el-text>
        </div>
      </div>
    </div>
    
    <template #footer>
      <div style="flex: auto">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleConfirmBind"
          :disabled="selectedRents.length === 0"
        >
          确认绑定 ({{ selectedRents.length }})
        </el-button>
      </div>
    </template>
  </el-drawer>

  <!-- 地点位置管理对话框 -->
  <LocationManageDialog 
    ref="locationManageDialog"
    @confirm="handleLocationConfirm"
  />
</template>

<script lang="ts" setup>
import { reactive, ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import LocationManageDialog from './LocationManageDialog.vue'

const emit = defineEmits(['bindSuccess'])

const dialogVisible = ref(false)
const searchText = ref('')
const selectedRents = ref<any[]>([])
const rentTableRef = ref()
const locationManageDialog = ref()

// 可用位置数据
const availableLocations = ref([
  { id: '1-1-1', fullPath: 'A栋办公楼 > 1楼 > 101会议室' },
  { id: '1-1-2', fullPath: 'A栋办公楼 > 1楼 > 102办公室' },
  { id: '1-1-3', fullPath: 'A栋办公楼 > 1楼 > 103休息室' },
  { id: '1-2-1', fullPath: 'A栋办公楼 > 2楼 > 201会议室' },
  { id: '1-2-2', fullPath: 'A栋办公楼 > 2楼 > 202办公室' },
  { id: '1-2-3', fullPath: 'A栋办公楼 > 2楼 > 203办公室' },
  { id: '1-3-1', fullPath: 'A栋办公楼 > 3楼 > 301办公室' },
  { id: '1-3-2', fullPath: 'A栋办公楼 > 3楼 > 302办公室' },
  { id: '2-1-1', fullPath: 'B栋生产楼 > 1楼 > 生产车间1' },
  { id: '2-1-2', fullPath: 'B栋生产楼 > 1楼 > 生产车间2' },
  { id: '2-2-1', fullPath: 'B栋生产楼 > 2楼 > 仓库1' },
  { id: '2-2-2', fullPath: 'B栋生产楼 > 2楼 > 仓库2' }
])

const groupInfo = reactive({
  id: '',
  groupName: '',
  usage: '',
  billingMethod: '',
  proportion: ''
})

// 房租数据 - 初始为空，用户可以手动输入
const availableRents = ref([
  {
    rentName: '',
    area: null,
    location: '',
    status: '可用',
    startDate: '2024-01-01',
    endDate: '2024-12-31'
  }
])

// 添加新的房租行
const addNewRentRow = () => {
  availableRents.value.push({
    rentName: '',
    area: null,
    location: '',
    status: '可用',
    startDate: '2024-01-01',
    endDate: '2024-12-31'
  });
};

// 过滤房租数据
const filteredRents = computed(() => {
  let rents = availableRents.value.filter(rent => rent.status === '可用')
  
  if (searchText.value) {
    const search = searchText.value.toLowerCase()
    rents = rents.filter(rent => 
      rent.rentName.toLowerCase().includes(search) ||
      rent.location.toLowerCase().includes(search)
    )
  }
  
  return rents
})

// 打开绑定抽屉
const openBindDialog = (group: any) => {
  Object.assign(groupInfo, {
    id: group.id,
    groupName: group.groupName,
    usage: group.usage,
    billingMethod: group.billingMethod,
    proportion: group.proportion
  })
  
  // 重置选择状态
  selectedRents.value = []
  searchText.value = ''
  
  // 初始化一个空的房租行，用于手动输入
  availableRents.value = [{
    rentName: '',
    area: null,
    location: '',
    status: '可用',
    startDate: '2024-01-01',
    endDate: '2024-12-31'
  }]
  
  dialogVisible.value = true
}

// 处理搜索
const handleSearch = () => {
  console.log('搜索房租:', searchText.value)
}

// 处理房租选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRents.value = selection
  console.log('选中的房租:', selection)
}

// 处理位置信息变化
const handleLocationChange = (row: any, index: number) => {
  console.log(`房租 ${row.rentName} 位置更新为:`, row.location)
}

// 打开地点位置管理对话框
const handleOpenLocationManage = () => {
  locationManageDialog.value?.openDialog()
}

// 处理位置管理确认
const handleLocationConfirm = (selectedItem: any) => {
  if (!selectedItem) {
    ElMessage.warning('未选择任何位置')
    return
  }
  
  // 检查是否已存在，避免重复
  const exists = availableLocations.value.find(item => item.id === selectedItem.id)
  if (!exists) {
    availableLocations.value.push({
      id: selectedItem.id,
      fullPath: selectedItem.fullPath || selectedItem.path
    })
    ElMessage.success('已添加位置到可选列表！')
  } else {
    ElMessage.warning('该位置已存在于可选列表中')
  }
}

// 确认绑定
const handleConfirmBind = async () => {
  // 检查所有选中的房租是否都填写了位置信息
  const rentsWithoutLocation = selectedRents.value.filter(rent => !rent.location || rent.location.trim() === '')
  
  if (rentsWithoutLocation.length > 0) {
    ElMessage.warning('请为所有选中的房租填写位置信息！')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要将 ${selectedRents.value.length} 个房租绑定到分组"${groupInfo.groupName}"吗？`,
      '确认绑定',
      {
        confirmButtonText: '确定绑定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    // 模拟绑定API调用
    const bindData = {
      groupId: groupInfo.id,
      groupName: groupInfo.groupName,
      rents: selectedRents.value.map(rent => ({
        rentName: rent.rentName,
        area: rent.area,
        location: rent.location,
        startDate: rent.startDate,
        endDate: rent.endDate
      }))
    }
    
    console.log('绑定数据:', bindData)
    
    // 模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 更新房租状态为已绑定
    selectedRents.value.forEach(selectedRent => {
      const rent = availableRents.value.find(r => r.rentName === selectedRent.rentName)
      if (rent) {
        rent.status = '已绑定'
      }
    })
    
    ElMessage.success(`成功绑定 ${selectedRents.value.length} 个房租到分组"${groupInfo.groupName}"！`)
    
    dialogVisible.value = false
    emit('bindSuccess', bindData)
    
  } catch {
    ElMessage.info('已取消绑定')
  }
}

// 重置数据
const reset = () => {
  selectedRents.value = []
  searchText.value = ''
  Object.assign(groupInfo, {
    id: '',
    groupName: '',
    usage: '',
    billingMethod: '',
    proportion: ''
  })
}

// 监听抽屉关闭，重置数据
watch(dialogVisible, (newVal) => {
  if (!newVal) {
    reset()
  }
})

defineExpose({
  dialogVisible,
  openBindDialog,
  reset
})
</script>

<style lang="scss" scoped>
.bind-content {
  padding: 0 16px;
  
  h3 {
    margin: 0 0 16px 0;
    color: #303133;
    font-size: 16px;
    font-weight: 600;
  }
  
  .group-info {
    background: #f8f9fa;
    padding: 16px;
    border-radius: 6px;
    border: 1px solid #e4e7ed;
  }
  
  .rent-selection {
    .el-table {
      :deep(.el-table__cell) {
        padding: 8px 0;
      }
    }
  }
}
</style>